package enterprise.manage.service.impl;

import enterprise.manage.dao.AuthorityDao;
import enterprise.manage.dao.RoleDao;
import enterprise.manage.dao.UserDao;
import enterprise.manage.entity.Authority;
import enterprise.manage.entity.Role;
import enterprise.manage.entity.User;
import enterprise.manage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: mojiajing
 * Date: 2011-7-1
 * Time: 14:05:37
 * Desc:
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AuthorityDao authorityDao;
    @Override
    public void registerUser(User user) {
        userDao.save(user);
    }

    @Override
    public boolean checkUserName(String userName) {
        User user = userDao.getByUserName(userName);
        if (user != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取用户权限
     * @param userId
     * @return
     */
    @Override
    public List<Authority> queryUserAuthorities(Long userId) {
         List<Authority> authorities = new ArrayList<Authority>();
        User user = userDao.get(userId);
        List<Role> roles = user.getRoles();
        for(Role role:roles){ 
           List<Authority> authorityList = role.getAuthorityList() ;
           authorities.addAll(authorityList);
        }
        return authorities;
    }

    @Override
    public List<String> queryUserAuthorityNames(Long userId) {
        List<Authority> authorities = queryUserAuthorities(userId);
        List<String>   authorityNames = new ArrayList();
        for(Authority authority :authorities){
             authorityNames.add(authority.getAuthorityName());
        }
        return authorityNames;
    }
}
